package cn.codergege.shiro.chapter6.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import cn.codergege.shiro.chapter6.model.User;

@Component
public class PasswordHelper {
	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "md5";
	private final int hashIterations = 2;
	
	public void encryptPassword(User user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		String password = new SimpleHash(
				algorithmName, 
				user.getPassword(), 
				ByteSource.Util.bytes(user.getCredentialsSalt()), 
				hashIterations).toHex();
		user.setPassword(password);
	}
}
